<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500" destroy-on-close @closed="$emit('closed')"
             align-center :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true">
    <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm">
      <el-row :gutter="1">
        <el-col :span="8">
          <el-form-item label="采购计划名称" prop="plan_name">
            <el-input v-model="form.plan_name" placeholder="请输入采购计划名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-col :span="8">
          <el-form-item label="供应商" prop="supplier_id">
              <el-select v-model="form.supplier_id" placeholder="请选择" filterable>
                  <el-option v-for="item in applyList" :key="item.id" :label="item.enterprise" :value="item.id"></el-option>
              </el-select>
          </el-form-item>
      </el-col> -->
      <el-form-item label="采购计划产品清单" prop="purchase_detail">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct" v-if="mode!='turn'">选择产品</el-button>
        <sc-form-table ref="table" v-model="form.purchase_detail" :addTemplate="addTemplate" placeholder="暂无数据" height="400" hideAdd show-summary>
          <el-table-column label="产品名称" align="center" prop="goods_name"></el-table-column>
          <el-table-column label="产品编号" align="center" prop="goods_code"></el-table-column>
          <el-table-column label="产品单位" align="center" prop="unit_name"></el-table-column>
          <el-table-column label="数量" prop="plan_num" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.plan_num" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="price" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="小计" prop="total_price" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.total_price" placeholder="小计" readonly></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
            </template>
          </el-table-column>
        </sc-form-table>
      </el-form-item>
      <el-form-item label="附件" prop="enclosure">
        <sc-upload-file v-model="form.enclosure" :limit="1">
          <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
        </sc-upload-file>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取 消</el-button>
      <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保 存</el-button>
      <el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
    </template>
  </el-dialog>
  <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';

export default {
  components: {selectGoods},
  emits: ['success', 'closed'],
  data() {
    return {
      mode: "add",
      titleMap: {
        add: '新增',
        mrpadd: '新增',
        sale: '新增',
        edit: '编辑',
        show: '查看',
      },
      visible: false,
      isSaveing: false,
      form: {
        id: "",
        plan_name: "",
        remark: "",
        enclosure: "",
        purchase_detail: [],
        is_check: 0
      },
      rules: {
        plan_name: [
          {required: true, message: '请输入采购计划名称'}
        ],
      },
      addTemplate: {},
      dialog: {
        goods: false,
      },
      applyList: [],
    }
  },
  mounted() {
    // this.getApply();
  },
  methods: {
    //显示
    open(mode = 'add') {
      this.mode = mode;
      this.visible = true;
      return this
    },
    //表单提交方法
    submit(e) {
      this.form.is_check = e
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true;
          var res = [];
          if (this.form.id) {
            res = await this.$API.procure.plan.edit.post(this.form);
          } else {
            res = await this.$API.procure.plan.add.post(this.form);
          }
          this.isSaveing = false;
          if (res.code == 1) {
            this.visible = false;
            this.$emit('success', this.form, this.mode)
            this.$message.success("操作成功")
          } else {
            this.$alert(res.message, "提示", {type: 'error'})
          }
        }
      })
    },
    //表单注入数据
    async setData(data) {
      this.form.id = data.id
      var res = await this.$API.procure.plan.detail.get({id: data.id});
      this.form.plan_name = res.data.plan_name
      this.form.remark = res.data.remark
      this.form.enclosure = res.data.enclosure
      let array = []
      res.data.purchase_detail.map(item => {
        array.push({
          id: item.id,
          goods_id: item.goods_id,
          goods_name: item.goods && item.goods.goods_name,
          unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
          goods_code: item.goods && item.goods.goods_code,
          plan_num: item.plan_num,
          price: item.price,
          total_price: item.total_price,
          remark: item.remark,
        })
      })
      this.form.purchase_detail = array
    },
    createSale(data) {
      let array = []
      data.map(item => {
        array.push({
          goods_id: item.goods_id,
          goods_name: item.goods_name,
          unit_name: item.unit_name,
          goods_code: item.goods_code,
          plan_num: item.number,
          price: item.price,
          total_price: Number(item.number) * Number(item.price),
        })
      })
      this.form.purchase_detail = array
    },
    // 选择产品
    checkProduct() {
      this.dialog.goods = true
      this.$nextTick(() => {
        this.$refs.goodsDialog.open('add')
      })
    },
    // 选择产品返回
    goodsUpdate(data) {
      let array = []
      data.map((item) => {
        array.push({
          goods_id: item.id,
          goods_name: item.goods_name,
          unit_name: item.unit && item.unit.unit_name,
          goods_code: item.goods_code,
          plan_num: 1,
          price: item.cost_price,
          total_price: item.cost_price
        })
      })
      let existingIds = this.form.purchase_detail.map(item => item.goods_id);
      for (let i = array.length - 1; i >= 0; i--) {
        if (existingIds.includes(array[i].goods_id)) {
          array.splice(i, 1);
        }
      }
      this.form.purchase_detail = [...this.form.purchase_detail, ...array]
    },
    // 供应商列表
    async getApply() {
      var res = await this.$API.purchase.apply.get();
      this.applyList = res.data
    },
    onFocus(event) {
      event.target.select();
    },
    totalCompute() {
      this.form.purchase_detail.map(item => {
        if (item.price && item.plan_num) {
          item.total_price = (Number(item.plan_num) * Number(item.price)).toFixed(2)
        }
      })
    },
    saleCome(table) {
      console.log('table :>> ', table);
      this.form.order_id = table.id
      let array = []
      table.product.map((item) => {
        array.push({
          goods_id: item.goods_id,
          goods_name: item.goods && item.goods.goods_name,
          unit_name: item.goods && item.goods.unit && item.goods.unit.unit_name,
          goods_code: item.goods && item.goods.goods_code,
          plan_num: item.sale_num,
          price: item.price,
          total_price: Number(item.sale_num) * Number(item.price),
          remark: item.remark,
        })
      })
      this.form.purchase_detail = array
    },
  }
}
</script>

<style>
</style>
